import { useUserStore } from '@/stores/user'

interface RequestOptions {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  header?: any
}

interface ResponseData<T = any> {
  code: number
  message: string
  data: T
}

const BASE_URL = import.meta.env.VITE_BASE_URL
const IMG_URL = import.meta.env.VITE_IMG_URL

// 创建请求函数
function request<T = any>(options: RequestOptions): Promise<T> {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore()
    
    // 合并请求头
    const header = {
      'Content-Type': 'application/json',
      ...options.header
    }
    
    // 如果有token，带上token
    if (userStore.token) {
      header['Authorization'] = `Bearer ${uni.getStorageSync('token')}`
    }

    // 处理URL
    let url = options.url
    url = url.startsWith('http') ? url : `${BASE_URL}${url}`

    uni.request({
      url,
      method: options.method || 'GET',
      data: options.data,
      header,
      success: (res: any) => {
        const response: ResponseData = res.data
        
        // 如果返回的状态码不是200，说明接口有问题，需要处理
        if (response.code !== 200) {
          // 如果是401，说明token过期，需要重新登录
          if (response.code === 401) {
            userStore.logout()
            // 不在这里自动登录，而是抛出错误
            reject(new Error('登录已过期'))
            return
          }
          
          uni.showToast({
            title: response.message,
            icon: 'none',
            duration: 2000
          })
          reject(response.message)
          return
        }
        resolve(response)
      },
      fail: (error) => {
        uni.showToast({
          title: error.errMsg || '请求失败',
          icon: 'none',
          duration: 2000
        })
        reject(error)
      }
    })
  })
}

export { BASE_URL, IMG_URL }
export default request